﻿$(function () {
    $("#txtMainStatus").autogrow();

    //gan submitfeed
    $("#btnSubmitMainStatus").click(function () {
        var content = EncodeContent($("div[name=txtMainStatus]").html());
        var timeStamp = new Date().getTime();
        $.post("/Home/AddNewPost", { 'content': content, 'timeStamp': timeStamp }, function (data) {
            if (data.indexOf("unsuccess") != 0) {
                var firstFeed = $("#feedStory div[name=feed]").first();
                if (firstFeed.length == 0) {
                    $("#thongbaofeed").remove();
                    $("#feedStory").append($(data));
                }
                else {
                    $(data).insertBefore(firstFeed);
                }
                $("#txtMainStatus").val("").css('height', 37);
                $("div[name=txtMainStatus]").html("");
            }
            else {
                var er = data.substring(10);
                if (er != "") {
                    if (er == 0) {
                        alert("Bạn phải nhập một kí tự");
                    }
                    else {
                        alert("Chỉ nhập tối đa 5000 kí tự");
                    }
                }
                else {
                    alert("Có lỗi, refresh trình duyệt và thử lại sau");
                }
            }
        })
        return false;
    })
    //Gan su kien onfocus cho cac textarea comment
    $("div[name=virtualbox]").live("click", function () {
        var commentBox = $(this).parents("[feedID]").first().find("div[name=cmtbox]");
        commentBox.css('display', 'block');
        commentBox.find("textarea").autogrow().first().focus();
        $(this).parent().css('display', 'none');
    })
    //Gan su kien cho nut lay them binh luan
    $("a[name=moreFeedComment]").live('click', function () {
        var divFeed = $(this).parents("[feedID]").first();
        var moreFeedCommentbtn = $(this);
        moreFeedCommentbtn.parent().find("img").css("display", "inline");
        var totalFeedComment = parseInt(divFeed.attr("totalcomment"));
        var feedID = divFeed.attr("feedID");
        var loaded = parseInt($(this).attr("loaded"));
        if (loaded >= totalFeedComment)
            return;
        var timeStamp = new Date().getTime();
        $.get("/Home/GetListFeedComment", { 'feedID': feedID, 'numberOfSkip': loaded, 'timeStamp': timeStamp }, function (data) {
            if (data == "NoMore") {
                moreFeedCommentbtn.parent().css('display', 'none');
            }
            else {
                var lstComment = $(data);
                loaded += lstComment.filter("div[name=comment]").length;
                moreFeedCommentbtn.attr("loaded", loaded);
                InsertCommentToFeed(feedID, lstComment, "Head");
                if (loaded >= totalFeedComment) {
                    moreFeedCommentbtn.parent().css('display', 'none');
                }
            }
            moreFeedCommentbtn.parent().find("img").css("display", "none");
        })
        return false;
    })

    //Gan su kien cho nut binh luan
    $("a[name=submitComment]").live("click", function () {
        var divFeed = $(this).parents("[feedID]").first();
        var feedID = divFeed.attr("feedID");
        var content = EncodeContent($("div[name=textComment_" + feedID + "]").html());
        var timeStamp = new Date().getTime();
        $.post("/Home/AddNewComment", { 'feedID': feedID, 'content': content, 'timeStamp': timeStamp }, function (data) {
            if (data.indexOf("unsuccess") != 0) {
                InsertCommentToFeed(feedID, $(data), "Tail");
                //Xoa noi dung trong comment box
                divFeed.find("textarea").css('height', 37);
                divFeed.find("textarea").val("").focus();
                $("div[name=textComment_" + feedID + "]").html("");
            }
            else {
                var er = data.substring(10);
                if (er != "") {
                    if (er == 0) {
                        alert("Bạn phải nhập một kí tự");
                    }
                    else {
                        alert("Chỉ nhập tối đa 5000 kí tự");
                    }
                }
                else {
                    alert("Có lỗi, refresh trình duyệt và thử lại sau");
                }
            }
        });
        return false;
    })
    //Gan su kien de hien thi nut xoa khi mouse move
    $("div[name=feed]").live({
        'mouseenter': function () {
            $(this).find("a[name=deleteFeed]").css('display', 'block');
        },
        'mouseleave': function () {
            $(this).find("a[name=deleteFeed]").css('display', 'none');
        }
    });
    $("div[name=comment]").live({
        'mouseenter': function () {
            $(this).find("a[name=deleteFeedComment]").parent().css('display', 'block');
        },
        'mouseleave': function () {
            $(this).find("a[name=deleteFeedComment]").parent().css('display', 'none');
        }
    });

    //Gan su kien cho cac nut delete
    $("a[name=deleteFeed]").live('click', function () {
        var feed = $(this).parents("[feedID]").first();
        var moreFeedCmt = feed.find("")
        var feedID = feed.attr("feedID");
        var timeStamp = new Date().getTime();
        $.post("/Home/DeleteFeed", { 'feedID': feedID, 'timeStamp': timeStamp }, function (data) {
            if (data == "success") {
                if (feed.next().attr("feedID") == feedID) {
                    feed.next().slideUp();
                    feed.next().remove();
                }
                feed.slideUp();
                feed.remove();
                var numberOfFeed = parseInt($("#feedStory").attr("numberOfFeed"));
                numberOfFeed -= 1;
                $("#feedStory").attr("numberOfFeed", numberOfFeed);
            }
            else {
                alert("Có lỗi, vui lòng refreh trình duyệt và thử lại");
            }
        })
        return false;
    })
    $("a[name=deleteFeedComment]").live('click', function () {
        var feedComment = $(this).parents("[feedCmtID]").first();
        var feedCommentID = feedComment.attr("feedCmtID");
        var timeStamp = new Date().getTime();
        $.post("/Home/DeleteFeedComment", { 'feedCommentID': feedCommentID, 'timeStamp': timeStamp }, function (data) {
            if (data == "success") {
                feedComment.slideUp();
                feedComment.remove();
                var loaded = parseInt($("a[name=moreFeedComment]").attr("loaded"));
                loaded -= 1;
                $("a[name=moreFeedComment]").attr("loaded", loaded);
            }
            else {
                alert("Có lỗi, vui lòng refreh trình duyệt và thử lại");
            }
        })
        return false;
    })
    //Lay feed lan dau tien khi pageload

    GetFeeds(true);

    //Lay them feed
    $("#moreFeed").live('click', function () {
        GetFeeds(false);
        return false;
    })
    self.setInterval("GetLatestNotification()", 5000);
    self.setInterval("GetLatestFeed()", 2000);
})

function InsertCommentToFeed(feedID, comment, position) {
    var anchor = $("div[name=childComments][feedID=" + feedID + "]").find("div[name=anchor_" + position + "]");
    if (position == "Head") {
        comment.insertAfter(anchor);
    }
    else {
        comment.insertBefore(anchor);
    }
}

//So feed mac dinh trong mot lan lay la :
DEFAULT_NUMBER_OF_FEED_PER_GET = 10;

// lay thong tin
function GetFeeds(first) {
    $("#loadingBar > img").css("display", "block");
    var numberOfFeed = parseInt($("#feedStory").attr("numberOfFeed")); // so feed hien tai dang co trong feedStory
    var timeStamp = new Date().getTime();
    $.get("/Home/GetListFeed", { 'numberOfSkip': numberOfFeed, 'timeStamp': timeStamp }, function (data) {
        if (data == "NoMore") {
            $("#feedStory").attr("numberOfFeed", -1);
            $("#moreFeed").parent().css('display', 'none');
            if (first) {
                $("#feedStory").html("<p id='thongbaofeed' style='font-weight:bold;font-size:13px;'>Chưa có tin tức nào từ bạn bè</p>")
            }
        }
        else {
            var newFeeds = $(data);
            numberOfFeed += newFeeds.filter("div[name=feed]").length  //-> dem so feed moi
            $("#feedStory").attr("numberOfFeed", numberOfFeed)
            $("#feedStory").append(data);
            if (newFeeds.filter("div[name=feed]").length < DEFAULT_NUMBER_OF_FEED_PER_GET) {
                $("#moreFeed").parent().css('display', 'none');
            }
            else {
                $("#moreFeed").parent().css('display', 'block');
            }
            if (first) {
                $("#moreFeed").click();
            }
        }
        $("#loadingBar > img").css("display", "none");
    });

    $(window).scroll(function () {
        if (window.pageYOffset + window.innerHeight + 100 > $("body").height()) {
            var numberOfFeed = $("#feedStory").attr("numberOfFeed");
            if (numberOfFeed > -1 && numberOfFeed < 30 && $("#loadingBar > img").css("display") != "none") {
                $("#moreFeed").click();
            }
        }
    });

}
var friendNotificationWaiting = false;
var courseNotificationWaiting = false;
var otherNotificationWaiting = false;

function GetLatestNotification() {
    if (!friendNotificationWaiting) {
        friendNotificationWaiting = true;
        $.post("/Notification/GetLatestNotification", { 'type': 'friend' }, function (data) {
            var elemntResult = $(data);
            if (elemntResult.attr("name") != "noMore") {
                elemntResult.find('li').each(function () {
                    var fid = $(this).attr("NotificationID");
                    if ($(".friendNotifications").find("[NotificationID =" + fid+"]").length == 0) {
                        if ($(".friendNotifications").find('ul > li').length != 0) {
                            $(".friendNotifications").find('ul > li:eq(0)').before($(this));
                        }
                        else {
                            if ($(".friendNotifications").find('ul').length != 0) {
                                $(".friendNotifications").find('ul').append($(this));
                            }
                            else {
                                $(".friendNotifications").find('[name=noMore]').remove();
                                $(".friendNotifications").find('.overview').append($(this));
                            }
                            //$(".friendNotifications").append($(this));
                        }
                    }
                });
                $("#otherNotifications").removeClass();
                $("#friendNotifications").addClass("notification");
                $(".friendNotifications").find(".vscrollbar").tinyscrollbar_update();
            }
            friendNotificationWaiting = false;
        })
    }
    if (!courseNotificationWaiting) {
        courseNotificationWaiting = true;
        $.post("/Notification/GetLatestNotification", { 'type': 'course' }, function (data) {
            var elemntResult = $(data);
            if (elemntResult.attr("name") != "noMore") {
                elemntResult.find('li').each(function () {
                    var cid = $(this).attr("NotificationID");
                    if ($(".courseNotifications").find("[NotificationID ="+cid+"]").length == 0) {
                        if ($(".courseNotifications").find('ul > li').length != 0) {
                            $(".courseNotifications").find('ul > li:eq(0)').before($(this));
                        }
                        else {
                            if ($(".courseNotifications").find('ul').length != 0) {
                                $(".courseNotifications").find('ul').append($(this));
                            }
                            else {
                                $(".courseNotifications").find('[name=noMore]').remove();
                                $(".courseNotifications").find('.overview').append($(this));
                            }
                            //$(".courseNotifications").append($(this));
                        }
                    }
                });
                $("#otherNotifications").removeClass();
                $("#courseNotifications").addClass("notification");
                $(".courseNotifications").find(".vscrollbar").tinyscrollbar_update();
            }
            courseNotificationWaiting = false;
        })
    }
    if (!otherNotificationWaiting) {
        otherNotificationWaiting = true;
        $.post("/Notification/GetLatestNotification", { 'type': 'other' }, function (data) {
            var elemntResult = $(data);
            if (elemntResult.attr("name") != "noMore") {
                elemntResult.find('li').each(function () {
                    var oid = $(this).attr("NotificationID");
                    if ($(".otherNotifications").find("[NotificationID ="+oid +"]").length == 0) {
                        if ($(".otherNotifications").find('ul > li').length != 0) {
                            $(".otherNotifications").find('ul > li:eq(0)').before($(this));
                        }
                        else {
                            if ($(".otherNotifications").find('ul').length != 0) {
                                $(".otherNotifications").find('ul').append($(this));
                            }
                            else {
                                $(".otherNotifications").find('[name=noMore]').remove();
                                $(".otherNotifications").find('.overview').append($(this));
                            }
                            //$(".otherNotifications").append($(this));
                        }
                    }
                });
                $("#otherNotifications").removeClass();
                $("#otherNotifications").addClass("notification");
                $(".otherNotifications").find(".vscrollbar").tinyscrollbar_update();
            }
            otherNotificationWaiting = false;
        })
    }
}
function GetLatestFeed() {
    if ($("#loadingBar > img").css("display") == "none") {
        $("#loadingBar > img").css("display", "block");
        var numberOfFeed = parseInt($("#feedStory").attr("numberOfFeed")); // so feed hien tai dang co trong feedStory
        var timeStamp = new Date().getTime();
        $.get("/Home/GetLatestFeed", function (data) {
            if (data != "NoMore") {
                var newFeeds = $(data);
                numberOfFeed += newFeeds.filter("div[name=feed]").length  //-> dem so feed moi
                $("#feedStory").attr("numberOfFeed", numberOfFeed)
                newFeeds.filter("[name=feed]").each(function () {
                    var feedID = $(this).attr("feedID");
                    if ($("#feedStory").find("[feedID=" + feedID + "]").length == 0) {
                        if ($("#feedStory").find("[name=feed]").length != 0) {
                            $("#feedStory").find("[name=feed]:eq(0)").before($(this));
                        }
                        else {
                            $("#thongbaofeed").remove();
                            $("#feedStory").append($(this));
                        }
                        var comment = newFeeds.filter("[name=childComments][feedID=" + feedID + "]");
                        if (comment.length != 0) {
                            $("#feedStory").find("[feedID=" + feedID + "]").after(comment);
                        }
                    }
                });
                //$("#feedStory").find("[name=feed]:eq(0)").before(data);
            }
            $("#loadingBar > img").css("display", "none");
        });
    }
}